package com.tich.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import com.tich.constant.ExceptionConstant;
import com.tich.constant.JwtConstant;
import com.tich.constant.RedisConstant;
import com.tich.constant.RequestConstant;
import com.tich.exception.UnauthorizedException;
import com.tich.gateway.config.AuthProperties;
import com.tich.properties.JwtProperties;
import com.tich.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否不需要拦截
        if(isExclude(request.getPath().toString())){
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        // 3.获取请求头中的token
        String token = null;
        List<String> headers = request.getHeaders().get(RequestConstant.AUTHORIZATION);
        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
        }
        // 4.校验并解析token
        Long userId = null;
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            // 5.获取用户信息（假设用户ID存储在"userId"声明中）
            userId = claims.get(JwtConstant.USERID, Long.class);
        } catch (JwtException | IllegalArgumentException e) {
            throw new UnauthorizedException(ExceptionConstant.INVALID_TOKEN);
        } catch (Exception e) {
            throw new UnauthorizedException(ExceptionConstant.NOT_AUTHORIZED);
        }
        //6.判断redis中是否存在该用户的jwt，如果存在就刷新时间
        String jwt = stringRedisTemplate.opsForValue().getAndExpire(RedisConstant.TOKEN_HEADER + userId, RedisConstant.TOKEN_TTL, TimeUnit.MINUTES);
        if(StrUtil.isBlank(jwt) || !jwt.equals(token)){
            throw new UnauthorizedException(ExceptionConstant.TIMEOUT_TOKEN);
        }
        // 7.如果有效，传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange webExchange = exchange.mutate()
                .request(builder -> builder.header(RequestConstant.USER_INFO, userInfo))
                .build();
        // 8.放行
        return chain.filter(webExchange);
    }

    //路径匹配器，用于匹配路径，判断该路径是否需要jwt令牌认证
    private boolean isExclude(String antPath) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}